<?php
require_once "gfun.php";
require_once "sqlop.php";

class initiative {
	public static $maclist="";
	public static function send($macno,$ip,$port,$data,$content=0){
		initiative::savemachinecommand($data,$ip,$port,1,$content);
		$client = new Swoole\Client(SWOOLE_SOCK_UDP);
		$client->set(array(
			'bind_address'     =>  '120.77.72.190',
			'bind_port'     =>  9508,
		));
		//连接到服务器
		if (!$client->connect($ip, $port, 0.5))
		{
			echo date("Y-m-d H:i:s",time())."----".$ip.":".$port."Send--Connnect Error:".gfun::strtohex($data)."\n";
			return -1;
		}
		//向服务器发送数据
		if (!$client->send($data))
		{
			echo date("Y-m-d H:i:s",time())."----".$ip.":".$port."Send--Send Error:".gfun::strtohex($data)."\n";
			return -2;
		}
		//关闭连接
		$client->close();
		//从服务器接收数据
		//$data = $client->recv();
		//if (!$data)
		//{
			echo date("Y-m-d H:i:s",time())."----".$ip.":".$port."Send--Successed:".gfun::strtohex($data)."\n";
			return 0;
		//}
		//file_put_contents('log.txt', date("Y-m-d H:i:s",time())."------>".$ip.":".$port."Received:".gfun::strtohex($data)."\r\n", FILE_APPEND); 
		//return $data;
	}
	public static function getcommand($macaddr,$command,$data,$addrtype){
		$line="3AA30000000".$addrtype.$macaddr;
		$line.=substr("000".dechex(strlen($command.$data)/2),-4);
		$line.=$command.$data;
		$line.=gfun::getcrc16($line);
		return gfun::hextostr($line);
	}
	static function getipport($macno){//根据机器号得到对应的IP和端口号
		$maclist=sqlop::select("ip,port,lastbeat from m_list where macno='".$macno."'");
		if(!empty($maclist)){
			while ($mac = $maclist->fetch_assoc()){
				return $mac;
			}
		}
	}
	static function savemachinecommand($data,$ip,$port,$type,$content="机器实时交互命令"){//保存机器交互命令
		$macno=gfun::getmacno($data);
		$sql="r_command (macno,ip,port,type,command,content,ctime) values(".$macno.",'".$ip."',".$port.",".$type.",'".gfun::strtohex($data)."','".$content."',UNIX_TIMESTAMP())";
		sqlop::insert($sql);
	}
}